//
//  TempUtilVC.swift
//  ZYA
//
//  Created by 邱仙凯 on 2022/8/3.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit

final class OfflineTool {
    
    private init() {}
    static let shared = OfflineTool()
    
    
    
    
}
struct OffLineModel {
    var id:String
    var offline_dt:String
    var template_data:String
    var pic_data:String
    var pic_data_details:String
    var image:VideoImg
    // 服务端用于存放切片的文件夹名称
    var clipFolder: String
    // 失败原因
    var failReason: String
    // 单据名称
    var menuName: String
}




final class OfflineFileBoard {
    private init() {}
    static let shared = OfflineFileBoard()
    
    /// 是否使用切片项目
    static func isUseFileClipPlatform() -> Bool {
        if PlatformManager.shared.platform == .haiXin {
            return true
        }
        return false
    }
    
    
    var dataArray = [OffLineModel]()
    // 真实文件数 (因为有切片,dataArray的数量会大于真实文件数)
    var realFileCount = 0
    fileprivate lazy var floatV:OfflineFileView = {
        let fv = OfflineFileView(frame:CGRect(x: 20, y: 70, width: 130, height: 50), imgStr: "piaojia")
        fv.clickAction = {
            
        
            self.uploadOffFineAction()
          
            
            
       
            
        }
        return fv
    }()
    func uploadOffFineAction() {
        if self.dataArray.count > 0 {
            
            getRealUploadingFileCount()
            
            let onem = self.dataArray.first!
            self.floatV.content.text = "\(self.realFileCount)个附件上传中..."
            KSNetwork.shared.doRequest(API.temp(.tempUploadFileClipApi(file_name: onem.image.name.unwrap, clip_num: onem.image.clipCount.unwrap, xuhao: onem.image.clipIndex.unwrap, pic_data: onem.pic_data, pic_data_details: onem.pic_data_details, templateData: onem.template_data, file: onem.image, clip_name: onem.clipFolder)), showHud: false, successHandle: { (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                   
                    FMDBHelper.shared.update(table: "OUTLINE_FILE", set: ["up_status"], with: ["1"], where: "id", equalto: onem.id)
                 
                  
                }
        

                self.dataArray.removeFirst()
                self.uploadOffFineAction()
                 
            }) { kserror in
                // 出错也不再传
                self.dataArray.removeFirst()
                self.uploadOffFineAction()
            }
            
        } else {
            self.hidden()
            // 只尝试一遍，没成功就等下次进来再尝试
//            self.checkOfflineFile()
        }
    }
    
    func checkOfflineFile() {
        self.dataArray.removeAll()
        do {
            let sql = "SELECT * FROM OUTLINE_FILE WHERE up_status = (?)"
            let resultSet = try FMDBHelper.shared.database.executeQuery(sql, values: ["0"])
              
          
           
            while resultSet.next() {
        
                if let id = resultSet.string(forColumn: "id"),
                   let offline_dt = resultSet.string(forColumn: "offline_dt"),
                   let template_data = resultSet.string(forColumn: "template_data"),
                   let pic_data = resultSet.string(forColumn: "pic_data"),
                   let pic_data_details = resultSet.string(forColumn: "pic_data_details"),
                   let img_name = resultSet.string(forColumn: "img_name"),
                   let img_data = resultSet.data(forColumn: "img_data"),
                   let xuhao = resultSet.string(forColumn: "xuhao"),
                   let clip_num = resultSet.string(forColumn: "clip_num"),
                   let clip_name = resultSet.string(forColumn: "clip_name"),
                   let clip_folder = resultSet.string(forColumn: "clip_folder"),
                   let fail_reason = resultSet.string(forColumn: "fail_reason"),
                   let menu_nm = resultSet.string(forColumn: "menu_nm")
                {
                     
                    var onexx = VideoImg()
                    onexx.name = img_name
                    onexx.data = img_data
                    onexx.clipIndex = intTran(xuhao)
                    onexx.clipCount = intTran(clip_num)
                    onexx.clipName = clip_name
                    
                    if img_name.contains("jpg") || img_name.contains("png") {
                        onexx.type = .image
                    } else if img_name.contains("mp4") {
                        onexx.type = .video
                    } else {
                        onexx.type = .file
                    }
                    let onem = OffLineModel(id:id,offline_dt: offline_dt, template_data: template_data, pic_data: pic_data, pic_data_details: pic_data_details, image: onexx, clipFolder: clip_folder, failReason: fail_reason, menuName: menu_nm)
                    self.dataArray.append(onem)
                        
                }
            }
            
            getRealUploadingFileCount()
             
        } catch {
         
        }
        
        if self.dataArray.count > 0 {
            self.show(str: "检测到您有\(self.realFileCount)个附件上传失败")
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.6) {
                self.uploadOffFineAction()
             }
        } else {
            self.hidden()
        }
        
    
    }
    
    
    /// 获取合并切片后的上传文件数
    func getRealUploadingFileCount() {
        var realFileNames = [String]()
        
        _ = self.dataArray.map({ one in
            let fName = one.image.name.unwrap
            var comNames = fName.components(separatedBy: "-")
            if comNames.count == 2 {
                // 被切片的文件
                if !realFileNames.contains(comNames.first!) {
                    realFileNames.append(comNames.first!)
                }
            } else {
                comNames = fName.components(separatedBy: ".")
                if comNames.count == 2 {
                    // 不需要切片的文件
                    if !realFileNames.contains(comNames.first!) {
                        realFileNames.append(comNames.first!)
                    }
                }
            }
        })
        
        realFileCount = realFileNames.count
    }
    
    func show(str:String) {
        floatV.content.text = str
        UIApplication.shared.keyWindow?.addSubview(floatV)
    }
    func hidden() {
        floatV.removeFromSuperview()
    }
}



class OfflineFileView: UIView {
    
    var clickAction:(()->())?
    
    private var lastPoint = CGPoint.zero
    
    private var pointInSelf = CGPoint.zero
    lazy var content:UILabel = {
        let v = UILabel(frame:self.bounds)
        v.textColor = .white
        v.textAlignment = .center
        v.numberOfLines = 2
        v.font = UIFont.systemFont(ofSize: 14)
        return v
    }()
    init(frame: CGRect,imgStr:String) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(kshex: "FA8072")
        self.layer.cornerRadius = 10
        self.addSubview(content)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()! as! UITouch
        lastPoint = touch.location(in: self.superview)
        pointInSelf = touch.location(in: self)
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()! as! UITouch
        let currentPoint = touch.location(in: self.superview)
        
        //计算当前的中心点
        let centerX = currentPoint.x - (frame.width/2 - pointInSelf.x)
        let centerY = currentPoint.y - (frame.height/2 - pointInSelf.y)
        //修改中心点的坐标
        let x = max(30.0, min(UIScreen.main.bounds.width - 30.0, centerX))
        let y = max(30.0, min(UIScreen.main.bounds.height - 30.0, centerY))
        
        center = CGPoint(x: x, y: y)
        
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()! as! UITouch
        let currentPoint = touch.location(in: self.superview)
        
        if __CGPointEqualToPoint(lastPoint, currentPoint) {
            /// 点击操作
            if let clickAction = self.clickAction {
                clickAction()
            }
            return
        }
        
        
        
        distanceLeftOrRightMarginNeedAnimationMove(isAnimation: true)
        
        
    }
    
    ///计算左右的距离并且是否需要动画移动
    private func distanceLeftOrRightMarginNeedAnimationMove(isAnimation: Bool) {
        
        let duartion = isAnimation ? 0.25:0
        
        let leftMargin = center.x
        let rightMargin = UIScreen.main.bounds.width - leftMargin
        
        let centerX = leftMargin < rightMargin ? 100.0 : UIScreen.main.bounds.width - 100.0
        
        UIView.animate(withDuration: duartion) {
            self.center = CGPoint(x: centerX, y: self.center.y)
        }
    }
}
